package com.studentbook.servlet;

import com.studentbook.service.StudentContactService;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * 删除联系人Servlet
 */
@WebServlet("/deleteContact")
public class DeleteContactServlet extends HttpServlet {
    private StudentContactService contactService = new StudentContactService();
    
    @Override
    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        // 设置请求和响应编码
        request.setCharacterEncoding("UTF-8");
        response.setContentType("text/html;charset=UTF-8");
        
        // 获取请求参数
        String idStr = request.getParameter("id");
        String studentId = request.getParameter("studentId");
        
        boolean success = false;
        
        // 根据ID删除
        if (idStr != null && !idStr.trim().isEmpty()) {
            try {
                int id = Integer.parseInt(idStr);
                success = contactService.deleteContactById(id);
            } catch (NumberFormatException e) {
                e.printStackTrace();
            }
        }
        // 根据学号删除
        else if (studentId != null && !studentId.trim().isEmpty()) {
            success = contactService.deleteContactByStudentId(studentId);
        }
        
        // 重定向到联系人列表页面
        response.sendRedirect(request.getContextPath() + "/listContacts");
    }
    
    @Override
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        doGet(request, response);
    }
}